//@author A0088498A
package logic;

import java.util.Collections;
import java.util.List;
import java.util.ArrayList;

import common.AttributeType;
import common.CommandType;
import common.Task;

import memory.Database;

/**
 * Suggestor is a singleton class implements the auto-completion for the system:
 * suggest the possible keywords based on what users have typed <br/>
 */

public class Suggestor {
	private static Suggestor INSTANCE = null;

	/**
	 * Private constructor to prevent other to instantiate more than 1 instances<br/>
	 */
	private Suggestor() {
	}

	/**
	 * Getter of the singleton <br/>
	 * 
	 * @return the singleton o this class
	 */
	public static Suggestor getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new Suggestor();
		}

		return INSTANCE;
	}

	/**
	 * Return a list of possible command word that match the prefix <br/>
	 * 
	 * @param prefix
	 *            to be searched
	 * @return a list of command words having the prefix
	 */
	public ArrayList<String> suggestCommandWord(String prefix) {
		ArrayList<String> suggestion = new ArrayList<String>();
		suggestion = CommandType.searchKeyword(prefix);
		return suggestion;
	}

	/**
	 * Return a list of possible words that match the prefix <br/>
	 * 
	 * @param prefix
	 *            to be searched
	 * @return a list of words having the prefix
	 */
	public ArrayList<String> suggest(String prefix) {
		ArrayList<String> suggestion = new ArrayList<String>();

		if (prefix != null) {
			if (prefix.contains("-")) {
				prefix = prefix.substring(1);
				suggestion = AttributeType.searchKeyword(prefix);
			} else {
				List<Task> relevantTask = Database.getInstance().searchTask(true, prefix);
				Collections.sort(relevantTask);

				// Filter out the task that does not start with the prefix
				// String
				for (Task task : relevantTask) {
					if (task.getName().toLowerCase().startsWith(prefix.toLowerCase())) {
						suggestion.add(task.getName());
					}
					if (task.getDescription().startsWith(prefix)) {
						suggestion.add(task.getDescription());
					}
				}
			}
		}

		return suggestion;
	}
}
